package utils;

import jdbc.DataSource;

import java.sql.*;

public final class JdbcUtils {

    private static DataSource dataSource = null;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver"); // 类加载到内存
            dataSource = DataSource.getInstance();
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    private JdbcUtils(){}

    public static Connection getConnection() throws SQLException {
        /*
        * 从数据库池中取连接
        * */
        return dataSource.getConnection();
    }

    public static void free(Statement stmt, Connection conn, ResultSet rs){
        /*
        * 连接放回数据库连接池
        * */
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                if (conn != null)
                    try {
                        conn.close(); // 使用代理模式 将MyConnection放到数据库连接池当中
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
            }
        }
    }
}
